package com.tboss.template.common.utils;

import java.io.IOException;
import java.io.InputStream;

import org.mozilla.universalchardet.UniversalDetector;

//Byte Order Mark
public class BOM {
	
	private InputStream is;
	
	public BOM(InputStream is) {
		this.is = is;
	}

	public String getCharSet(){
		String rtnValue = "EUC-KR";
		
		try {
			UniversalDetector detector = new UniversalDetector(null);
			byte[] buf = new byte[4096];
			int nread;
			while ((nread = this.is.read(buf)) > 0 && !detector.isDone()) {
				detector.handleData(buf, 0, nread);
			}
			detector.dataEnd();
			
			String encoding = detector.getDetectedCharset();
			if (encoding != null) {
				rtnValue = encoding;
			}/*else {
				System.out.println("No encoding detected.");
			}*/
			
			detector.reset();
			
		} catch (IOException e){ e.getMessage();
		} finally {	
			try { if(this.is != null) this.is.close();
			} catch (IOException e) { e.printStackTrace();
			}
		}
		
		/*try {
			byte[] BOM = new byte[4];
			this.is.read(BOM, 0, 4);
			
			System.out.println("@@@");
			System.out.println(BOM[0] & 0xFF);
			System.out.println(BOM[1] & 0xFF);
			System.out.println(BOM[2] & 0xFF);
			System.out.println("@@@");
			
			if( (BOM[0] & 0xFF) == 0xEF && (BOM[1] & 0xFF) == 0xBB && (BOM[2] & 0xFF) == 0xBF ) rtnValue = "UTF-8";
			else if( (BOM[0] & 0xFF) == 0xFE && (BOM[1] & 0xFF) == 0xFF ) rtnValue = "UTF-16BE";
			else if( (BOM[0] & 0xFF) == 0xFF && (BOM[1] & 0xFF) == 0xFE ) rtnValue = "UTF-16LE";
			else if( (BOM[0] & 0xFF) == 0x00 && (BOM[1] & 0xFF) == 0x00 && (BOM[0] & 0xFF) == 0xFE && (BOM[1] & 0xFF) == 0xFF ) rtnValue = "UTF-32BE";
			else if( (BOM[0] & 0xFF) == 0xFF && (BOM[1] & 0xFF) == 0xFE && (BOM[0] & 0xFF) == 0x00 && (BOM[1] & 0xFF) == 0x00 ) rtnValue = "UTF-32LE";
			
			System.out.println(rtnValue);
			System.out.println("@@@");
			this.is.reset();
			
		} catch (IOException e) { e.getMessage();
		} finally {	
			try { if(this.is != null) this.is.close();
			} catch (IOException e) { e.printStackTrace();
			}
		}*/
		
		return rtnValue;
	}

}
